package com.reporter;

import java.awt.Color;
import java.awt.Desktop;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.FocusAdapter;
import java.awt.event.FocusEvent;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.imageio.ImageIO;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SwingWorker;
import javax.swing.UIManager;
import javax.xml.parsers.ParserConfigurationException;

import org.xml.sax.SAXException;

import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;



import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.HashMap;
import java.util.Map;

import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JRResultSetDataSource;
import net.sf.jasperreports.engine.JasperCompileManager;
import net.sf.jasperreports.engine.JasperExportManager;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.JasperReport;
import net.sf.jasperreports.engine.design.JasperDesign;
import net.sf.jasperreports.engine.xml.JRXmlLoader;


public class PanelReporter extends JPanel {
	private JTextField txtStatus;
	private JButton btnFolderSelect;
	private JButton btnStart;
	final boolean bOpenFolderAfter = false;
	private ProgressDialog progressDialog;
	
	List<String> lstCurDir = new ArrayList<String>();
	List<String> lstPngFiles = new ArrayList<String>();

	private JCheckBox chckbxOverrideSampling;
	private JCheckBox chckbxOpenFolder;

	public PanelReporter(JFrame parent, String sPanelTitle) {
		setBackground(UIManager.getColor("TableHeader.background"));
		
		progressDialog = new ProgressDialog(parent);
		
		GridBagLayout gridBagLayout = new GridBagLayout();
		gridBagLayout.columnWidths = new int[]{28, 0, 0, 104, 0, 0, 0, 0, 0};
		gridBagLayout.columnWeights = new double[]{0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0};
		gridBagLayout.rowHeights = new int[]{0, 0, 0, 0, 0, 0, 0, 0};
		gridBagLayout.rowWeights = new double[]{0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0};
		setLayout(gridBagLayout);
		
		setBorder(BorderFactory.createTitledBorder(BorderFactory.createLineBorder(Color.gray), sPanelTitle));
		
		chckbxOverrideSampling = new JCheckBox("Override Sampling");
		chckbxOverrideSampling.setToolTipText("Manually specify the RGB color when converting to transparent background");
		GridBagConstraints gbc_chckbxOverrideSampling = new GridBagConstraints();
		gbc_chckbxOverrideSampling.anchor = GridBagConstraints.WEST;
		gbc_chckbxOverrideSampling.insets = new Insets(0, 0, 5, 5);
		gbc_chckbxOverrideSampling.gridx = 3;
		gbc_chckbxOverrideSampling.gridy = 0;
		add(chckbxOverrideSampling, gbc_chckbxOverrideSampling);
		
		DefaultTableModel model;
		String col[] = {"PNG List"};
		model = new DefaultTableModel(col,5);
		
		chckbxOpenFolder = new JCheckBox("Open Folder");
		chckbxOpenFolder.setSelected(true);
		chckbxOpenFolder.setToolTipText("Open the 'TRANSPARENT' folder after batch conversion");
		GridBagConstraints gbc_chckbxOpenFolder = new GridBagConstraints();
		gbc_chckbxOpenFolder.anchor = GridBagConstraints.WEST;
		gbc_chckbxOpenFolder.insets = new Insets(0, 0, 5, 5);
		gbc_chckbxOpenFolder.gridx = 3;
		gbc_chckbxOpenFolder.gridy = 1;
		add(chckbxOpenFolder, gbc_chckbxOpenFolder);
		
		btnFolderSelect = new JButton("PNG Folder");
		btnFolderSelect.setToolTipText("Select the folder that contains all the .png files");
		btnFolderSelect.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				lstPngFiles = getPngFolder();
				}
		});
		
		GridBagConstraints gbc_btnFolderSelect = new GridBagConstraints();
		gbc_btnFolderSelect.gridwidth = 2;
		gbc_btnFolderSelect.insets = new Insets(0, 0, 5, 5);
		gbc_btnFolderSelect.gridx = 0;
		gbc_btnFolderSelect.gridy = 4;
		add(btnFolderSelect, gbc_btnFolderSelect);
		
		btnStart = new JButton("Start");
		btnStart.setToolTipText("execute batch conversion. all converted files saved to 'TRANSPARENCY' folder located in above selection");
		btnStart.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
//				if (lstPngFiles.size() > 0)	
//				removeBackgroundColor(lstPngFiles);
//				else
//					txtStatus.setText("Selected folder does not contain .png files");
				
				CreateReport();
				
			}
		});
		
		GridBagConstraints gbc_btnStart = new GridBagConstraints();
		gbc_btnStart.gridwidth = 2;
		gbc_btnStart.fill = GridBagConstraints.BOTH;
		gbc_btnStart.insets = new Insets(0, 0, 5, 5);
		gbc_btnStart.gridx = 0;
		gbc_btnStart.gridy = 5;
		add(btnStart, gbc_btnStart);
		
		txtStatus = new JTextField(10);
		txtStatus.setText("status");
		txtStatus.setEditable(false);
		GridBagConstraints gbc_txtStatus = new GridBagConstraints();
		gbc_txtStatus.fill = GridBagConstraints.HORIZONTAL;
		gbc_txtStatus.anchor = GridBagConstraints.WEST;
		gbc_txtStatus.gridwidth = 9;
		gbc_txtStatus.gridx = 0;
		gbc_txtStatus.gridy = 7;
		add(txtStatus, gbc_txtStatus);
		

	///error check manual entry
		entryFieldErrChk();
	}
	
	private void removeBackgroundColor(final List<String> pngFiles) {

		progressDialog.setMaximum(100);
		progressDialog.setVisible(true);

		SwingWorker<Void, Integer> worker = new SwingWorker<Void, Integer>() {

			@Override
			protected void done() {

				progressDialog.setVisible(false);

			}

			@Override
			protected void process(List<Integer> progress) {

				int percentage = progress.get(progress.size() - 1);

				progressDialog.setValue(percentage);
				progressDialog.setString(Integer.toString(percentage) + "%");

			}

			@Override
			protected Void doInBackground() throws IndexOutOfBoundsException, ParserConfigurationException, SAXException, IOException {

				String sDir = pngFiles.get(0).substring(0, pngFiles.get(0).lastIndexOf("\\"))+"\\TRANSPARENT";
				File dir = new File(sDir);
				
				int i=0;
				
				if (!dir.isDirectory())
					dir.mkdir();

				for (String sFilename : pngFiles) {

					BufferedImage image;
					///progress bar percentage
					publish((int)(Math.round((((float)i)/((float)(pngFiles.size())))*100)));
					i++;
				}

				///job complete
				txtStatus.setText("Completed!");
				
				///open folder
				if(chckbxOpenFolder.isSelected() && Desktop.isDesktopSupported())	{
					    Desktop.getDesktop().open(dir);
				}
				
				return null;
			}
		};
		///run multi-thread
		worker.execute();
	}
	
	
	private void CreateReport()	{
		
		Connection conn;
		
		try {
			Class.forName("com.mysql.jdbc.Driver");
			conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/tpom?user=tpom&password=tpom@");
			System.out.println("Loading Report Designs");
			InputStream input = new FileInputStream(new File("jrxml/BasicReport.jrxml"));
			JasperDesign jasperDesign = JRXmlLoader.load(input);

			System.out.println("Compiling Report Designs");
			JasperReport jasperReport = JasperCompileManager.compileReport(jasperDesign);

			System.out.println("Creating JasperPrint Object");
			Map<String, String> parameters = new HashMap<String, String>();
			parameters.put("ReportTitle", "PDF JasperReport");

			System.out.println("Filling Report to File");
			JasperPrint jasperPrint = JasperFillManager.fillReport(jasperReport, null, conn);

			//Exporting the report
			OutputStream output = new FileOutputStream(new File("report/BasicReport.pdf"));
			JasperExportManager.exportReportToPdfStream(jasperPrint, output);

			System.out.println("Report Generation Complete");
			conn.close();
			} catch (FileNotFoundException e) {
			e.printStackTrace();
			} catch (JRException e) {
			e.printStackTrace();
			} catch (ClassNotFoundException e) {
			e.printStackTrace();
			} catch (SQLException e) {
			e.printStackTrace();
			}
	}
	
		
		
	
	
	private List<String> getPngFolder() {

		// JFileChooser chooser = new JFileChooser(System.getProperty("user.dir"));
		
		JFileChooser chooser;
		
		if (lstCurDir.size()>0)	{
		 	chooser = new JFileChooser(lstCurDir.get(0));
		}
		else	{
			chooser = new JFileChooser(System.getProperty("user.dir"));
			lstCurDir.add("");
		}

		
		List<String> lstPngFiles = new ArrayList<String>();

		chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
		int option = chooser.showOpenDialog(PanelReporter.this);

		if(option == JFileChooser.APPROVE_OPTION) {
			txtStatus.setText("folder:" + ((chooser.getSelectedFile()!=null)? chooser.getSelectedFile().getAbsoluteFile():"nothing"));
			String sFolderLocation = chooser.getSelectedFile().getAbsoluteFile().toString();
			File nf = new File(sFolderLocation);
			chooser.setCurrentDirectory(nf);
			
			lstCurDir.set(0, chooser.getCurrentDirectory().getAbsolutePath());
//			System.out.println(chooser.getCurrentDirectory().getAbsolutePath());
			
			File[] filesInDirectory = chooser.getCurrentDirectory().listFiles();

			for (File file : filesInDirectory) {
				if(file.getName().toLowerCase().contains(".png"))	{
					lstPngFiles.add(sFolderLocation + "\\" + file.getName());
				}
			}
		}

		if(option == JFileChooser.CANCEL_OPTION) {
			txtStatus.setText("canceled.");
		}
		return lstPngFiles;
	}

	
	private void entryFieldErrChk() {
		
	    ///only allow for max 3 characters
	    final int iTextFieldMax = 3;

	}
	
}
